import { createRouter, createWebHistory } from "vue-router";
import { useUserStore } from "./stores/user";

const router = createRouter({
    history: createWebHistory(),
    routes: [
        {path: '/', component: () => import('./views/Home.vue')},
        {path: '/login', component: () => import('./views/Login.vue')},
        {path: '/register', component: () => import('./views/Register.vue')},
        {path: '/students', component: () => import('./views/StudentListView.vue')},
        {path: '/profile', 
            component: () => import('./views/StudentProfile.vue'),
            meta: { requiresAuth: true, role: 'student' }
        },
        {path: '/students/edit/:id', 
            component: () => import('./views/StudentEdit.vue'), 
            props: true, 
            meta: { requiresAuth: true, role: 'teacher' }
        },
        { path: '/admin', 
            component: () => import('./views/AdminDashboard.vue'),
            meta: { requiresAuth: true, role: 'admin'}
        },
        {
            path: '/teacher_profile',
            component: () => import('./views/TeacherProfile.vue'),
            meta: { requiresAuth: true, role: 'teacher'}
        }
    ]
})

//路由守卫
router.beforeEach((to, from, next) => {
    const userStore = useUserStore()
    if (to.meta.requiresAuth) {
        if (!userStore.isLoggedIn) {
            next('/login')
        } else if (to.meta.role && userStore.role != to.meta.role) {
            next('/')
        } else {
            next()
        }
    } else {
        next()
    }
})

export default router